﻿using System.Collections.Generic;

namespace Red.Launcher.ViewModels.Workspaces.Database
{
    public class AssignedUser : Record, IRecordWrapper
    {
        #region Private Data

        private int _userId;

        #endregion Private Data

        #region Inherited Properties

        public override Metadata Metadata { get { return METADATA; } }
        public override string Icon { get { return "appbar_clothes_shirt"; } }
        public override IEnumerable<object> Values { get { return new List<object>() { UserId }; } }

        public Record ActualRecord => FindRecord( typeof( User ), UserId );
        public Metadata ActualMetadata => User.METADATA;

        #endregion Inherited Properties

        #region Public Properties

        public static Metadata METADATA { get; private set; }

        public int UserId
        {
            get { return _userId; }
            set { _userId = value; }
        }

        #endregion Public Properties

        #region C-Tor

        static AssignedUser()
        {
            METADATA = new Metadata()
            {
                Table = "AssignedGroups",
                Keys = new List<string>() { User.METADATA.ForeignKey },
                CreateDefault = () => { return null; },
                CreateFromDatabaseRow = ( Dictionary<string, object> data ) =>
                {
                    return new AssignedUser()
                    {
                        Id = (int)data[ "ag_id" ],
                        UserId = (int)data[ "id" ],
                        Name = (string)data[ "username_win" ]
                    };
                },
                GenerateSelectSql = GenerateSelectSql
            };
        }

        public AssignedUser() : base()
        {
        }

        public AssignedUser( User user ) : base()
        {
            UserId = user.Id;
            Name = user.Name;
        }

        #endregion C-Tor

        #region Private Methods

        private static Sql.Select GenerateSelectSql( Record parent )
        {
            Sql.Select.Table source = Sql.Select.CreateTable( User.METADATA.Table, "u" );

            Sql.Select query = new Sql.Select();
            query.Sources.Add( source );

            Sql.IAlias joinSource = query.AddStandardChildJoin( User.METADATA, AssignedUser.METADATA, source, AssignedUserGroup.METADATA, parent.Id );

            query.AddColumn( "id", joinSource, "ag_id" );
            query.AddColumn( "*", source );

            return query;
        }

        #endregion Private Methods
    }
}
